package scparser.factory.primitiveFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import lib.common.Constants;
import model.GenericMesh;
import model.Normal;
import model.Points;
import model.Shader;
import model.Triangles;
import model.Uvs;
import model.primitive.Primitive;
import raycast.Scene;
import scparser.ParserHelper;

public class GenericMeshFactory extends PrimitiveFactory {
	private String name;
	private Shader shader;
	private Points points;
	private Triangles triangles;
	private Normal normal;
	private Uvs uvs;
	
	public GenericMeshFactory(Scene scene) {
		super.scene = scene;
	}


	
	public Primitive create(List<String> block) throws PrimitiveFactoryException {
		String line = null;
		Iterator<String> it = block.iterator();
		
		try {
			while (it.hasNext()) {
				line = it.next().trim();
				
				if (line.endsWith(Constants.S_CLOSE)) {
					break;
				}
				
				if (line.startsWith("name")) {
					this.name = ParserHelper.takeString(line, "name");
				}
				
				if (line.startsWith("shader")) {
					String shaderName = ParserHelper.takeString(line, "shader");
					if ((this.shader = getShader(shaderName)) == null) {
						throw new PrimitiveFactoryException("shader " + shaderName + " not found");
					}			
				}
				
				if (line.startsWith("triangles")) {
					int num = Integer.parseInt(ParserHelper.takeString(line, "triangles"));
					String[] values = new String[num];
					
					for (int i = 0; i < num; i++) {
						if (it.hasNext()) {
							values[i] = it.next();
						} else {
							new PrimitiveFactoryException("error in triangles number");
						}
					}
					
					this.triangles = new Triangles(num, values);
				}
				
				// for future extension, normal and uvs
				if (line.startsWith("uvs")) {
					this.uvs = null;
				}
				
				if (line.startsWith("normal")) {
					this.normal = null;
				}
			}
		} catch (IOException e) {
			throw new PrimitiveFactoryException(e.getMessage());
		} catch (NumberFormatException e) {
			throw new PrimitiveFactoryException(e.getMessage());
		}

		return new GenericMesh(this.shader.getName(), this.name, this.triangles, this.points, 
				this.normal, this.uvs);
	}


	public static void main(String[] args) {
		String a = "  a  b";
		System.out.println(a.trim());
	}

}
